// static/js/auth.js

// 认证相关函数
function getAuthToken() {
return localStorage.getItem('token');
}

function getUserInfo() {
const userInfoStr = localStorage.getItem('userInfo');
return userInfoStr ? JSON.parse(userInfoStr) : null;
}

function checkAuth() {
const token = getAuthToken();
const userInfo = getUserInfo();

if (!token || !userInfo) {
window.location.href = '/login';
return false;
}
return true;
}

function getAuthHeaders() {
const token = getAuthToken();
return {
'Content-Type': 'application/json',
'Authorization': token
};
}

async function authFetch(url, options = {}) {
if (!checkAuth()) {
throw new Error('未登录');
}

const defaultOptions = {
headers: getAuthHeaders()
};

const mergedOptions = {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers
}
};

const response = await fetch(url, mergedOptions);

if (response.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('userInfo');
window.location.href = '/login';
throw new Error('登录已过期，请重新登录');
}

return response;
}

// 退出登录
async function logout() {
try {
const token = getAuthToken();
if (token) {
await authFetch('/api/auth/logout', {
method: 'POST'
});
}
} catch (error) {
console.error('退出登录失败:', error);
} finally {
localStorage.removeItem('token');
localStorage.removeItem('userInfo');
window.location.href = '/login';
}
}

// 页面加载时检查认证
function initAuth() {
if (!checkAuth()) {
return false;
}

// 显示当前用户信息
const userInfo = getUserInfo();
if (userInfo) {
const userElement = document.getElementById('current-user');
if (userElement) {
userElement.textContent = userInfo.username;
}
}

return true;
}

// 为所有链接添加认证头
function setupAuthForLinks() {
// 拦截所有链接点击事件
document.addEventListener('click', function(e) {
const target = e.target.closest('a');
if (target && target.href) {
const url = new URL(target.href);
// 如果是内部链接且不是登录页面
if (url.origin === window.location.origin && !url.pathname.includes('/login')) {
e.preventDefault();

// 检查认证
if (!checkAuth()) {
return;
}

// 使用带认证的跳转
window.location.href = target.href;
}
}
});
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
initAuth();
//setupAuthForLinks();
});